package com.huawei.config;


import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.i18n.AbstractLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.regex.Pattern;
 
/**
 * 设置语言环境解析器
 * <p>
 * 注意：bean的name需要为{@link DispatcherServlet#LOCALE_RESOLVER_BEAN_NAME}，才能覆盖默认的语言环境解析器
 */
@Slf4j
@Component(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
public class DemoLocaleResolver extends AbstractLocaleResolver {
    
    /** local信息key, 此key对应的value应为【语言_国家】或【语言_地区】，如：【zh_CN】 */
    private static final String LOCAL_KEY = "lang";
    
    private static final Pattern LOCAL_PATTERN = Pattern.compile("[a-z]+_[A-Z]+");
    
    public DemoLocaleResolver() {
    }
    
    @NonNull
    @Override
    public Locale resolveLocale(@NonNull HttpServletRequest request) {
        // 从请求头中拿前端传的local信息
        String localInfo = request.getHeader(LOCAL_KEY);
        if (StringUtils.isBlank(localInfo) && request.getServletPath().startsWith("/i18n/test")) { // 这里之所以加一个"/i18n/test"前缀的判断，是因为在本demo中，只有这几个前缀的url是演示国际化的，其余的与本演示不相关
            System.err.println("测试validation国际化，请在请求头中通过lang设置当前语言环境。 如：lang=zh_CN 、lang=zh_TW、lang=en_US之类的");
            throw new IllegalArgumentException("请填写必要请求头");
        }
        boolean legal = LOCAL_PATTERN.matcher(localInfo).matches();
        Locale locale;
        if (legal) {
            try {
                int splitSignIndex = localInfo.indexOf("_");
                String language = localInfo.substring(0, splitSignIndex);
                String country = localInfo.substring(splitSignIndex + 1);
                locale = new Locale(language, country);
                return locale;
            } catch (Exception e) {
                log.warn("parse Local instance occur error. e.getMessage() -> {}", e.getMessage());
            }
        }
        Locale defaultLocale = getDefaultLocale();
        locale = defaultLocale != null ? defaultLocale : request.getLocale();
        if (locale == null) {
            locale = Locale.SIMPLIFIED_CHINESE;
        }
        return locale;
    }
    
    @Override
    public void setLocale(@NonNull HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException("Cannot change HTTP lang header - use a different locale resolution strategy");
    }
    
}